import {
  Component,
  OnInit,
  ElementRef,
  ViewChild,
  AfterViewInit,
} from "@angular/core";
import { FetchService } from "../../../core/net/fetch.service";
import { differenceInCalendarDays } from "date-fns";
import * as _ from "lodash";
import { UtilService } from "../../../core/util/util.service";
import { ActivatedRoute, Router } from "@angular/router";
import { DispatchPlanService } from "../dispatch-plan.service";
import {
  HttpClient,
  HttpEvent,
  HttpEventType,
  HttpRequest,
  HttpResponse,
} from "@angular/common/http";
// import { UploadXHRArgs } from "ng-zorro-antd/upload";
// import { NzMessageService } from "ng-zorro-antd";
import { NzMessageService, NzModalService, UploadXHRArgs } from 'ng-zorro-antd';

import { DomSanitizer, SafeResourceUrl } from "@angular/platform-browser";


@Component({
  selector: "app-slt-dispatch-plan-year-add",
  templateUrl: "./slt-dispatch-plan-year-add.component.html",
  styleUrls: ["./slt-dispatch-plan-year-add.component.scss"],
})
export class yearPlanAddComponent implements OnInit {
  serverUrl = (window as any).environment.reportUrl;
  uploadUrl = `${(window as any).environment.apiBaseUrl
    }sys/yjqYearPlan/import`;
  uploadUrlActive = `${(window as any).environment.apiBaseUrl
    }sys/yjqYearPlan/import`;
  sectionid: string = JSON.parse(localStorage.userInfo).sectionId;

  ifReportSrc: SafeResourceUrl;
  selectedItem = {
    name: "引黄灌区各干渠取水指标",
    value: "ExcelMapper-wrsExcelYhgqPlan",
    type: "",
    reportName: "引黄灌区各干渠取水指标",
  };
  editType = "view";
  year = "";
  name = "";
  exportType = "";
  radioValue = "1";
  radioShowType = false;

  constructor(
    private fetchService: FetchService,
    private util: UtilService,
    private router: Router,
    private routerInfo: ActivatedRoute,
    private http: HttpClient,
    private message: NzMessageService,
    private sanitizer: DomSanitizer
  ) {
    console.log(this.routerInfo.snapshot.queryParams);
    this.editType = this.routerInfo.snapshot.queryParams["openType"];
    this.year = this.routerInfo.snapshot.queryParams["selectYears"];
    this.name = this.routerInfo.snapshot.queryParams["planName"];
  }

  ngOnInit() {
    // this.selectItem(this.selectedItem);
    this.queryInfo();
  }

  downLoadExcel(): void {
    if (!this.radioShowType) {
      const param = {
        y: this.year,
      };


      this.fetchService
        .export("sys/yjqYearPlan/exportTemplate", param)
        .subscribe((res: any) => {
          const blob = new Blob([res], {
            type:
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
          });
          const elink = document.createElement("a");
          elink.download = `${this.name}.xlsx`;
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        });
    } else {
      const param = {
        reportYear: this.year,
      };

      this.fetchService
        .export(
          "/base/wrsScheduleCropStructureIrrArea/export/" + this.radioValue,
          param
        )
        .subscribe((res: any) => {
          const blob = new Blob([res], {
            type:
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
          });
          const elink = document.createElement("a");
          elink.download = `${this.selectedItem.reportName}.xlsx`;
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        });
    }
  }

  customReq = (item: UploadXHRArgs) => {
    if (!this.radioShowType) {
      this.uploadUrl = `${(window as any).environment.apiBaseUrl
        }sys/yjqYearPlan/import`;
    } else {
      this.uploadUrl = `${(window as any).environment.apiBaseUrl
        }base/wrsScheduleCropStructureIrrArea/import/${this.radioValue}`;
    }
    const formData = new FormData();
    const importUrl = "";
    formData.append("file", item.file as any);
    formData.append("y", this.year);

    const req = new HttpRequest("POST", this.uploadUrl, formData, {
      reportProgress: true,
      withCredentials: false,
    });
    return this.http.request(req).subscribe(
      (event: HttpEvent<{}>) => {
        if (event instanceof HttpResponse) {
          if (event.body["data"]) {
            if (event.body["data"]["body"]["succeed"]) {
              this.message.success("数据上传成功");
              // this.selectItem(this.selectedItem);
              this.queryInfo();
            } else {

            }
          } else {
            this.message.error("数据上传失败，请查看错误信息重新上传");
            this.fetchService
              .export(
                `comm/file/down/${event.body["data"]["body"]["writebackAppendixId"]}`,
                {}
              )
              .subscribe((res: any) => {
                const blob = new Blob([res], {
                  type:
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
                });
                const elink = document.createElement("a");
                elink.download = `${this.selectedItem.reportName}-错误提示.xlsx`;
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href); // 释放URL 对象
                document.body.removeChild(elink);
              });
          }

          // this.getGridData();
        }
      },
      (err) => {
        item.onError!(err, item.file!);
        this.message.error("上传失败，请重新上传");
      }
    );
  }
  queryInfo() {
    const link = `${this.serverUrl}preview?_u=wrs:跃进渠年计划报表2.ureport.xml&_t=6&y=${this.year}&section_id=${this.sectionid}`;

    this.ifReportSrc = this.sanitizer.bypassSecurityTrustResourceUrl(link);
  }
  back(): void {
    this.router.navigate(["/dispatch-plan/year-plan"]);
  }
}
